package com.tanhua.dubbo.api.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineUtils;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineUtils timeLineUtils;

    @Override
    public void saveMovements(Movement movement) {
        movement.setPid(idWorker.getNextId("movement"));
        mongoTemplate.save(movement);
        timeLineUtils.saveTimeLine(movement);
    }

    @Override
    public PageResult findMovements(Integer page, Integer pagesize, Long userId, Integer state) {
        Criteria criteria = new Criteria();
        if (userId != null) {
            criteria.and("userId").is(userId);
        }
        if (state != null) {
            criteria.and("state").is(state);
        }
        Query query = new Query(criteria);
        long counts = mongoTemplate.count(query, Movement.class);
        query.with(Sort.by(Sort.Order.desc("created"))).skip((page - 1) * pagesize).limit(pagesize);
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page.longValue(), pagesize.longValue(), counts, movements);
    }

    @Override
    public PageResult findFriendsMovements(Integer page, Integer pagesize, Long userId) {
        Query query1 = new Query(Criteria.where("friendId").is(userId));
        long counts = mongoTemplate.count(query1, MovementTimeLine.class);
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query1, MovementTimeLine.class);
        List<ObjectId> movementIds = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
        Query query2 = new Query(Criteria.where("id").in(movementIds));
        query2.with(Sort.by(Sort.Order.desc("created"))).skip((page - 1) * pagesize).limit(pagesize);
        List<Movement> movementList = mongoTemplate.find(query2, Movement.class);
        return new PageResult(page.longValue(), pagesize.longValue(), counts, movementList);
    }

    @Override
    public List<Movement> findByPids(List<Long> pidList) {
        Query query = new Query(Criteria.where("pid").in(pidList));
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return movementList;
    }

    @Override
    public List<Movement> ramdomMovements(Integer pagesize) {
        TypedAggregation typedAggregation = new TypedAggregation(Movement.class, Aggregation.sample(pagesize));
        AggregationResults<Movement> movements = mongoTemplate.aggregate(typedAggregation, Movement.class);
        return movements.getMappedResults();
    }

    @Override
    public Movement findById(String movementId) {
        Movement movement = mongoTemplate.findById(new ObjectId(movementId), Movement.class);
        return movement;
    }

    @Override
    public void update(String movementId, Integer state) {
        Query query = new Query(Criteria.where("id").is(new ObjectId(movementId)));
        Update update = new Update();
        update.set("state", state);
        mongoTemplate.updateFirst(query, update, Movement.class);
    }

    @Override
    public void updateByIds(String[] ids, Integer state) {
        for (String id : ids) {
            Query query = new Query(Criteria.where("id").is(new ObjectId(id)));
            Update update = new Update();
            update.set("state", state);
            mongoTemplate.updateFirst(query, update, Movement.class);
        }
    }
}